package com.datang.pet.service.impl;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-06-12 09:39
 * @notify
 * @version 1.0
 */

import com.datang.pet.common.ossUtils.DeleteFile;
import com.datang.pet.common.ossUtils.OssUtil;
import com.datang.pet.common.redis.RedisTool;
import com.datang.pet.common.utils.MD5;
import com.datang.pet.common.utils.StringUtils;
import com.datang.pet.mapper.*;
import com.datang.pet.pojo.*;
import com.datang.pet.mapperExtend.ResourceMapperExtend;
import com.datang.pet.mapperExtend.TalkMapperExtend;
import com.datang.pet.mapperExtend.UserInfoMapperExtend;
import com.datang.pet.service.MessageService;
import com.datang.pet.service.TalkService;
import com.datang.pet.vo.AddTalkRequest;
import com.datang.pet.vo.GetTalkListResponse;
import com.datang.pet.vo.TalkInfoResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TalkServiceImpl implements TalkService {

    @Autowired
    private TalkMapper talkMapper;

    @Autowired
    private ResourceMapperExtend resourceMapperExtend;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private TalkMapperExtend talkMapperExtend;

    @Autowired
    private TalkSearchRecordMapper talkSearchRecordMapper;

    @Autowired
    private UserMessageMapper userMessageMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserJurisdictionMapper userJurisdictionMapper;

    @Autowired
    private TalkComplainRecordMapper talkComplainRecordMapper;

    @Autowired
    private TalkLikeRecordMapper talkLikeRecordMapper;

    @Autowired
    private UserInfoMapperExtend userInfoMapperExtend;


    @Autowired
    private RedisTool redisTool;

    @Autowired
    private DeleteFile deleteFile;

    /*
     * @author 顶风少年
     * @date 2019/6/13 8:47
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param addTalkRequest
     * @result void
     * @notify 添加喵文 成功推送消息
     * version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTalk(AddTalkRequest addTalkRequest) throws Exception {
        //md5解密userId(普通用户)
        try {
            addTalkRequest.setUserId(MD5.decryptData(addTalkRequest.getUserId()));
        } catch (Exception e) {
            throw new Exception("userId解密出错！");
        }

        //创建喵文对象
        Talk talk = new Talk();
        BeanUtils.copyProperties(addTalkRequest, talk);
        talk.setId(StringUtils.getId());
        String resourceId = StringUtils.getId();
        talk.setResourceId(resourceId);
        talk.setTalkDate(new Date());
        talk.setBan("0");
        talk.setLikeQuantity(0);
        talk.setCommentQuantity(0);
        talk.setComplaninQuantity(0);
        try {
            talkMapper.insert(talk);
        } catch (Exception e) {
            throw new Exception("添加喵文失败");
        }

        List<Resource> resourceList = addTalkRequest.getResourceList();
        //给每一个资源添加id
        for (Resource r : resourceList) {
            r.setId(resourceId);
            //喵文类型
            String type = addTalkRequest.getTalkType();
            if (type.equals("0")) {
                //0是图片,给src添加 图片的url
                r.setSrc(OssUtil.getBucketUrl(1) + r.getSrc());
            } else if (type.equals("1") || type.equals("2")) {
                //1,2是视频,给src添加 图片的url
                r.setSrc(OssUtil.getBucketUrl(2) + r.getSrc());
            }
        }
        try {
            resourceMapperExtend.addResourceList(resourceList);
        } catch (Exception e) {
            throw new Exception("添加资源失败");
        }

        //移除redis中的数据
        redisTool.remove("talkListByUserId"+addTalkRequest.getUserId());
        //发送消息
        messageService.getMessage(talk.getUserId(), "1");
    }

    /*
     * @author 顶风少年
     * @date 2019/6/13 8:52
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param time
     * @result java.util.List<GetTalkListResponse>
     * @notify 获取喵文列表
     * version 1.0
     */
    public List<GetTalkListResponse> getTalkList(Date time) throws Exception {
        try {
            return talkMapperExtend.getTalkList(time);
        } catch (Exception e) {
            throw new Exception("获取喵文列表失败");
        }
    }

    /*
     * @author 顶风少年
     * @date 2019/6/21 15:11
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param userId
     * @result java.util.List<GetTalkListResponse>
     * @notify 通过用户id获取用户发布的喵文
     * version 1.0
     */
    public List<GetTalkListResponse> getTalkListByUserId(String userId) throws Exception {

        try {
            return talkMapperExtend.getTalkListByUserId(userId);
        } catch (Exception e) {
            throw new Exception("获取喵文列表失败");
        }
    }


    /*
     * @author 顶风少年
     * @date 2019/6/13 14:29
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param keyword
     * @param time
     * @result java.util.List<GetTalkListResponse>
     * @notify 搜索喵文
     * version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
    public List<GetTalkListResponse> getTalkListByKeyword(String userId, String keyword, Date time) throws Exception {
        //md5解密userId(普通用户)
        try {
            userId = MD5.decryptData(userId);
        } catch (Exception e) {
            throw new Exception("userId解密出错！");
        }
        List<GetTalkListResponse> talkListByKeyword = null;
        try {
            talkListByKeyword = talkMapperExtend.getTalkListByKeyword(keyword, time);

        } catch (Exception e) {
            throw new Exception("搜索喵文失败");
        }

        //设置搜索记录
        TalkSearchRecord talkSearchRecord = new TalkSearchRecord();
        talkSearchRecord.setId(StringUtils.getId());
        talkSearchRecord.setUserId(userId);
        talkSearchRecord.setDate(new Date());
        talkSearchRecord.setKeyword(keyword);
        if (talkListByKeyword.isEmpty()) {
            talkSearchRecord.setNotHave("1");
        } else {
            talkSearchRecord.setNotHave("0");
        }
        try {
            talkSearchRecordMapper.insert(talkSearchRecord);
        } catch (Exception e) {
            throw new Exception("添加搜索喵文记录失败");
        }

        return talkListByKeyword;
    }

    /*
     * @author 顶风少年
     * @date 2019/6/13 23:30
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param label
     * @result java.util.List<GetTalkListResponse>
     * @notify 获取喵文相关推荐
     * version 1.0
     */
    public List<GetTalkListResponse> getTalkLikeLabel(String label,String talkId) throws Exception {

        try {
            return talkMapperExtend.getTalkLikeLabel(label,talkId);

        } catch (Exception e) {
            throw new Exception("搜索喵文失败");
        }
    }

    /*
     * @author 顶风少年
     * @date 2019/6/13 14:55
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @result java.util.List<TalkSearchRecord>
     * @notify 获取喵文搜索记录
     * version 1.0
     */
    public List<TalkSearchRecord> getSearchRecordList() throws Exception {

        try {
            return talkMapperExtend.getSearchRecordList();
        } catch (Exception e) {
            throw new Exception("获取搜索记录失败");
        }

    }


    /*
     * @author 顶风少年
     * @date 2019/6/13 18:10
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param talkId
     * @param userId
     * @result TalkInfoResponse
     * @notify 获取喵文详情
     * version 1.0
     */
    public TalkInfoResponse getTalkInfo(String talkId, String userId) throws Exception {

        try {
            return talkMapperExtend.getTalkInfo(talkId, userId);
        } catch (Exception e) {
            throw new Exception("获取喵文详情失败");
        }

    }

    /*
     * @author 顶风少年
     * @date 2019/6/14 10:05
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param userId
     * @param talkId
     * @param complainContent
     * @result void
     * @notify 举报喵文
     * version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
    public void complainTalk(String userId, String talkId, String complainContent) throws Exception {
        //用户权限
        List<UserJurisdiction> userJurisdictions = null;
        try {
            UserJurisdictionExample userJurisdictionExample = new UserJurisdictionExample();
            UserJurisdictionExample.Criteria criteria = userJurisdictionExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andScopeEqualTo("talk:ban");
            userJurisdictions = userJurisdictionMapper.selectByExample(userJurisdictionExample);
        } catch (Exception e) {
            throw new Exception("查询用户权限失败");
        }

        //查询用户是否有删除喵文权限
        if (userJurisdictions.isEmpty()) {
            //如果没有删除权限则添加举报记录
            try {
                //插入举报内容
                TalkComplainRecord talkComplainRecord = new TalkComplainRecord();
                talkComplainRecord.setId(StringUtils.getId());
                talkComplainRecord.setUserId(userId);
                talkComplainRecord.setTalkId(talkId);
                talkComplainRecord.setComplainContent(complainContent);
                talkComplainRecord.setComplainDate(new Date());
                talkComplainRecordMapper.insertSelective(talkComplainRecord);
            } catch (Exception e) {
                throw new Exception("添加举报记录失败");
            }

            //喵文添加举报数
            try {
                talkMapperExtend.increaseTalk(talkId, "3");
            } catch (Exception e) {
                throw new Exception("添加举报数失败");
            }

        } else {
            try {
                //设置属性和删除
                Talk talk = new Talk();
                talk.setId(talkId);
                talk.setBan("1");
                talkMapper.updateByPrimaryKeySelective(talk);
            } catch (Exception e) {
                throw new Exception("禁止喵文失败");
            }
        }


    }

    @Transactional(rollbackFor = Exception.class)
    public void likeTalk(String userId, String talkId, String type, String talkUserId) throws Exception {
        //点赞规则:如果一个用户给另一个用户的作品点赞,发表作品的用户总点赞数+1
        //取消则-1.取消点赞没有消息通知,点赞则有消息通知.如果取消点赞后,又点赞
        //同样只操作用户总点赞数.消息记录只会增加不会减少
        //点赞:参考抖音点赞系统
        if (type.equals("1")) {
            //增加点赞记录
            try {
                TalkLikeRecord talkLikeRecord = new TalkLikeRecord();
                talkLikeRecord.setId(StringUtils.getId());
                talkLikeRecord.setTalkId(talkId);
                talkLikeRecord.setUserId(userId);
                talkLikeRecord.setLikeDate(new Date());
                talkLikeRecordMapper.insert(talkLikeRecord);
            } catch (Exception e) {
                throw new Exception("添加点赞记录失败");
            }

            try {
                //发布喵文作者总点赞数+1
                userInfoMapperExtend.contrLikeQuantity(talkUserId, "1");
            } catch (Exception e) {
                throw new Exception("用户总点赞+1失败");
            }

            try {
                //喵文点赞+1
                talkMapperExtend.increaseTalk(talkId, "1");
            } catch (Exception e) {
                throw new Exception("喵文点赞+1失败");
            }
            System.out.println(userId);
            System.out.println(talkUserId);
            if(!userId.equals(talkUserId)){
                try {
                    UserMessage userMessage = new UserMessage();
                    userMessage.setId(StringUtils.getId());
                    userMessage.setIsRead("0");
                    userMessage.setUserId(talkUserId);
                    userMessage.setMessage("");
                    userMessage.setMessageDate(new Date());
                    userMessage.setModelId(talkId);
                    userMessage.setMessageType("2");
                    userMessage.setExtent1(userId);
                    userMessageMapper.insert(userMessage);
                } catch (Exception e) {
                    throw new Exception("点赞成功,增加消息失败");
                }
                //发送消息
                messageService.getMessage(talkUserId, "2");
            }

        } else {
            //删除点赞记录
            try {
                TalkLikeRecordExample talkLikeRecordExample = new TalkLikeRecordExample();
                TalkLikeRecordExample.Criteria criteria = talkLikeRecordExample.createCriteria();
                criteria.andTalkIdEqualTo(talkId);
                criteria.andUserIdEqualTo(userId);
                talkLikeRecordMapper.deleteByExample(talkLikeRecordExample);
            } catch (Exception e) {
                throw new Exception("删除点赞记录失败");
            }

            try {
                //发布喵文作者总点赞数-1
                userInfoMapperExtend.contrLikeQuantity(talkUserId, "2");
            } catch (Exception e) {
                throw new Exception("用户总点赞-1失败");
            }

            try {
                //喵文点赞-1
                talkMapperExtend.decrementTalk(talkId, "1");
            } catch (Exception e) {
                throw new Exception("喵文点赞-1失败");
            }


        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteTalk(String userId,String id) throws Exception{
        //查询日志
        Talk talk = talkMapper.selectByPrimaryKey(id);
        String resource = talk.getResourceId();
        //删除日志
        talkMapper.deleteByPrimaryKey(id);

        ResourceExample resourceExample = new ResourceExample();
        ResourceExample.Criteria criteria= resourceExample.createCriteria();
        criteria.andIdEqualTo(resource);

        //查询资源
        List<Resource> resources = null;
        resources= resourceMapper.selectByExample(resourceExample);

        //删除资源
        resourceMapper.deleteByExample(resourceExample);


        for (Resource resource1 : resources) {
            Double size =  resource1.getSize();
            if(size==null){
                deleteFile.deleteSingFile(resource1.getSrc(),1);
            }else{
                deleteFile.deleteSingFile(resource1.getSrc(),2);
            }
        }
        //移除redis中的数据
        redisTool.remove("talkListByUserId" + userId);
    }
}
